# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

from __future__ import absolute_import
from __future__ import division
# from __future__ import print_function

import time
import argparse
from importlib import util
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
import json
import os
from PIL import Image
from tensorflow.python import pywrap_tensorflow



os.environ['TF_CPP_MIN_LOG_LEVEL']='1'

def load_graph(model_file):
  graph = tf.compat.v1.Graph()
  graph_def = tf.compat.v1.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph



def read_tensor_from_image_file(file_name,
                                input_height=299,
                                input_width=299,
                                input_mean=0,
                                input_std=255):
  input_name = "file_reader"
  output_name = "normalized"

  file_reader = tf.io.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(
        file_reader, channels=3, name="png_reader")
  elif file_name.endswith(".gif"):
    image_reader = tf.squeeze(
        tf.image.decode_gif(file_reader, name="gif_reader"))
  elif file_name.endswith(".bmp"):
    image_reader = tf.image.decode_bmp(file_reader, name="bmp_reader")
  else:
    image_reader = tf.image.decode_jpeg(
        file_reader, channels=3, name="jpeg_reader")
  # float_caster = tf.cast(image_reader, tf.float32)

  float_caster = tf.image.convert_image_dtype(image_reader, dtype=tf.float32)
  float_caster = tf.image.central_crop(float_caster, central_fraction=0.875)

  image = tf.expand_dims(float_caster, 0)
  image = tf.compat.v1.image.resize_bilinear(image, [input_height, input_width])
  # image = tf.squeeze(image, [0])
  image = tf.subtract(image, 0.5)
  image = tf.multiply(image, 2.0,name="normalized")
  # normalized = tf.divide(tf.subtract(image, [input_mean]), [input_std])


  sess = tf.compat.v1.Session()
  result = sess.run(image)

  return result




def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.io.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    # print(l)  # classes
    label.append(l.rstrip())
  return label


def main():

  file_p = "./test_video/t/"
  file_l = os.listdir(file_p)
  print(file_l)

  mn = 171126

  model_file = "inference_model/porn_%s.pb" % mn
  label_file = "labels.txt"


  input_layer = "input:0"
  output_layer = "InceptionV4/Logits/Predictions:0"
  # output_layer = "resnet_v2_50/predictions/Reshape_1"
  # output_layer = "vgg_16/fc8/squeezed"
  # output_layer = "resnet_v2_50/predictions/Softmax"

  graph = load_graph(model_file)

  with tf.compat.v1.Session(graph=graph) as sess:
    with open('%sres%s.txt'% (file_p,mn),'w+') as f:

      for file in file_l:
        file_name = file_p + file
        if file_name.endswith('.txt'):
            continue

        t = read_tensor_from_image_file(
            file_name)
        input_operation, output_operation = get_io_op(graph, input_layer, output_layer)
        results = sess.run(output_operation, {
              input_operation: t
        })


        res = make_res(label_file, results)
        ress = file + ':'+ str(res) +'\n'
        f.write(ress)
        f.flush()
        print(ress)


def make_res(label_file, results ):
  results = np.squeeze(results)
  top_k_index = results.argsort()[-2:][::-1][0]
  labels = load_labels(label_file)
  res = labels[top_k_index], results
  # img = draw_detections_class(v[1], res)

  return res


def get_io_op(graph, input_layer, output_layer):
  input_name = "import/" + input_layer
  output_name = "import/" + output_layer
  # oplist = graph.get_operations()
  input_operation = graph.get_tensor_by_name(input_name)
  output_operation = graph.get_tensor_by_name(output_name)
  return input_operation, output_operation




if __name__ == "__main__":

  main()







